package com.qunar.wan.web.controller;

import com.google.common.base.Preconditions;
import com.qunar.wan.common_api.model.Classify;
import com.qunar.wan.common_api.model.SubClassify;
import com.qunar.wan.common_api.model.User;
import com.qunar.wan.common_api.model.enums.Role;
import com.qunar.wan.common_api.service.AdminLogService;
import com.qunar.wan.common_api.service.CacheService;
import com.qunar.wan.common_api.service.SubClassifyService;
import com.qunar.wan.common_api.service.UserService;
import com.qunar.wan.web.controller.common.AbstractController;
import com.qunar.wan.web.filter.AuthenticationController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * User: hangyu.shen Date: 13-11-29 Time: 上午9:32
 * <p/>
 * 管理员或超级管理员增删子分类活动或查看活动
 */
@Controller
@RequestMapping("admin/subClassify")
public class SubClassifyController extends AbstractController implements AuthenticationController {
    @Resource
    private SubClassifyService subClassifyService;
    @Resource
    private AdminLogService adminLogService;
    @Resource
    private UserService userService;
    @Resource
    private CacheService cacheService;

    /**
     * 显示所有大分类活动类别
     * 
     * @return
     */
    @RequestMapping("/showAllClassify")
    public ModelAndView getAllClassify() {
        // List<Classify> listClassifies = classifyService.selectAll();
        List<Classify> listClassifies = cacheService.readClasCache();
        return new ModelAndView("activity/showAllClassify", "listClassifies", listClassifies);
    }

    /**
     * 显示请求的大分类活动的分类活动类别
     * 
     * @param supId 当前子分类活动的父分类id
     * @param msg 在jsp中显示的消息
     * @param request
     * @return
     */
    @RequestMapping("/showSubClassify")
    public ModelAndView getSubClassifyBySupId(@RequestParam(value = "supId") int supId, String msg,
            HttpServletRequest request) {
        // List<SubClassify> listSubClassifies = subClassifyService.selectListBySupId(supId);
        List<SubClassify> listSubClassifies = cacheService.readSubsCache(supId);
        ModelMap map = new ModelMap();
        map.put("msg", msg);
        map.put("listSubClassifies", listSubClassifies);
        // 获取cookie信息并插入日志
        int adminId = Preconditions.checkNotNull(userService.currentLogonUser()).getId();
        // Classify classify = classifyService.selectClassifyById(supId);
        Classify classify = cacheService.readSingleClassifyCache(supId);
        String str = String.format("查看'%s'活动子分类活动列表信息", classify.getClaName());
        adminLogService.insertAdminLog(adminId, str);
        return new ModelAndView("activity/showSubClassify", "listSubClassifies", map);
    }

    /**
     * 添加子分类活动，如果数据库中有重名则添加失败，跳转addSubClassify.jsp页面重新添加；如果添加成功则跳转大分类活动显示页
     * 
     * @param request
     * @param supId 当前子分类活动的父分类id
     * @param map 返回jsp中的信息
     * @return
     */
    @RequestMapping(value = "/addSubClassify", method = RequestMethod.POST)
    public Object insertSubClassify(HttpServletRequest request, @RequestParam(value = "supId") int supId, ModelMap map) {
        Preconditions.checkNotNull(supId);
        String subName = request.getParameter("subName");
        Preconditions.checkNotNull(subName);
        map.put("supId", supId);
        List<SubClassify> list = subClassifyService.selectListBySubName(subName);
        if (!list.isEmpty()) {
            // 如果数据库的sub_classify表中存在与subName同名的记录，则添加子活动名失败
            map.put("msg", "您添加的子活动名已存在，请重新添加");
            // 数据库中有同名记录，跳转请求的当前页
            return "activity/addSubClassify";
        } else {
            // 获取cookie信息
            int adminId = Preconditions.checkNotNull(userService.currentLogonUser()).getId();
            // 添加子活动并插入日志
            subClassifyService.insertSubClassifyByTran(adminId, supId, subName);
            // 数据库中无同名记录，允许子活动添加
            return getSubClassifyBySupId(supId, "添加子活动成功！", request);
        }
    }

    /**
     * 删除子分类活动，删除后跳转对应的子分类活动显示页
     * 
     * @param id 子分类活动的id
     * @param supId 当前子分类活动的父分类id
     * @param request
     * @return
     */
    @RequestMapping("/deleteSubClassify")
    public ModelAndView deleteSubClassify(@RequestParam(value = "id") int id, @RequestParam(value = "supId") int supId,
            HttpServletRequest request) {
        // 获取cookie信息并插入日志（需要事务处理）
        int adminId = Preconditions.checkNotNull(userService.currentLogonUser()).getId();
        // 删除子活动并插入日志
        subClassifyService.deleteSubClassifyByTran(adminId, supId, id);
        // return "redirect:/subClassify/showSubClassify.do?supId=" + supId;
        return getSubClassifyBySupId(supId, "", request);
    }

    /**
     * 添加子活动的中间跳转
     * 
     * @param supId 父类活动id
     * @param map 返回给jsp页面的信息
     * @return
     */
    @RequestMapping("/addSubClassifyReq")
    public String addSubClassify(@RequestParam(value = "supId") int supId, ModelMap map) {
        map.put("supId", supId);
        return "activity/addSubClassify";
    }

    @Override
    public boolean isAuthenticated(String pathInfo, ServletRequest req) {
        User user = userService.currentLogonUser();
        if (user == null) {
            return false;
        }
        if (user.getRole() == Role.MANAGER || user.getRole() == Role.SUPERMANAGER) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isCheckRequired(ServletRequest req) {
        return true;
    }

}
